import React, { useState } from 'react';
import styled from 'styled-components';
import { Layout } from 'components/Layout';
import { CategorySection } from 'views/Money/CategorySection';
import { NoteSection } from 'views/Money/NoteSection';
import { NumPadSection } from 'views/Money/NumPadSection';
import { TagsSection } from 'views/Money/TagsSection';
import { useRecords } from 'hooks/useRecords';
import { Toast } from 'antd-mobile';

const MyLayout = styled(Layout)`
  display: flex;
  flex-direction: column;
`;

type Category = '-' | '+';

const defaultFormData = {
  tagIds: [] as number[],
  note: '',
  category: '-' as Category,
  amount: 0,
};

const CategoryWrapper = styled.div`
  background: #c4c4c4;
`;

export default function Money() {
  const [selected, setSelected] = useState(defaultFormData);
  const { addRecord } = useRecords();
  const onChange = (obj: Partial<typeof selected>) => {
    setSelected({ ...selected, ...obj });
  };
  const submit = () => {
    if (addRecord(selected)) {
      Toast.info('保存成功', 2);
    }
    setSelected(defaultFormData);
  };
  return (
    <MyLayout scrollTop={9999}>
      <TagsSection
        value={selected.tagIds}
        onChange={tagIds => onChange({ tagIds })}
      />
      <NoteSection
        value={selected.note}
        onChange={note => onChange({ note })}
      />
      <CategoryWrapper>
        <CategorySection
          value={selected.category}
          onChange={(category: Category) => onChange({ category })}
        />
      </CategoryWrapper>
      <NumPadSection
        value={selected.amount}
        onChange={amount => onChange({ amount })}
        onOk={submit}
      />
    </MyLayout>
  );
}
